<template>
  <img class="cg-image" :src="data" />
</template>

<script setup lang="ts">
// 直接显示图片组件，通过path地址去查询缓存
import { ref, watch, onMounted } from 'vue'
import { DispatchResult } from '../../tools/index'
import Api from '../../components/tools/api'

// 定义组件名称
defineOptions({
  name: 'cg-image'
})

// 定义props
const props = withDefaults(
  defineProps<{
    path: string | undefined
  }>(),
  {
    path: undefined
  }
)

// 定义响应式数据
const data = ref<string | undefined>(undefined)

// 加载图片数据
async function load() {
  data.value = undefined
  if (!props.path) {
    return
  }
  try {
    let result = await Api.send(`/material/find`, {
      path: props.path
    })
    DispatchResult(result, {
      onSuccess: (resData) => {
        data.value = resData.data
      }
    })
  } catch (error) {
    console.log(error)
  }
}

// 监听path变化
watch(
  () => props.path,
  () => {
    load()
  }
)

// 组件挂载时加载图片
onMounted(() => {
  load()
})
</script>
